#include<iostream>
#include<vector>
using namespace std;

class Node {
public:
    int val;
    Node* left;
    Node* right;

    Node() {}

    Node(int _val) {
        val = _val;
        left = NULL;
        right = NULL;
    }

    Node(int _val, Node* _left, Node* _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};

void _treeToDoublyList(Node* cur, Node*& prev) {
    if (cur == nullptr)
        return;

    _treeToDoublyList(cur->left, prev);

    if (prev)
        prev->right = cur;

    cur->left = prev;

    prev = cur;
    _treeToDoublyList(cur->right, prev);
}

Node* treeToDoublyList(Node* root) {
    if (root == nullptr)
        return nullptr;

    Node* prev = nullptr;
    _treeToDoublyList(root, prev);

    Node* head = root;
    while (head->left) {
        head = head->left;
    }

    Node* end = root;
    while (end->right) {
        end = end->right;
    }

    head->left = end;
    end->right = head;

    return head;
}

int main()
{
    return 0;
}